package com.gitee.linmt.service;

import com.gitee.linmt.entity.Role;
import com.gitee.linmt.entity.UserInfo;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义 UserDetailService，根据用户名获取用户信息.
 *
 * @author <a href="mailto:lin-mt@outlook.com">lin-mt</a>
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    
    private static final Set<String> USERS;
    
    static {
        USERS = new HashSet<>();
        USERS.add("大秃驴");
        USERS.add("小和尚");
    }
    
    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        if (USERS.contains(username)) {
            final UserInfo userInfo = new UserInfo();
            userInfo.setId(1L);
            userInfo.setUsername(username);
            // 此处需要自己实现自己的需求，从数据库或其他地方获取用户的权限
            // 暂时就将拥有的权限设置为用户名，为什么我这里不说是设置角色呢，后面我不懒的话会有博客说明
            final Set<Role> roles = new HashSet<>();
            roles.add(new Role().setRoleName("ROLE_" + username));
            userInfo.setAuthorities(roles);
            // 我们在注册用户加密密码的时候，使用的方式要跟我们注入 Spring Security 的方式相同
            userInfo.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("password"));
            return userInfo;
        }
        throw new UsernameNotFoundException("该用户不存在");
    }
}